const app = getApp();
var wxbarcode = require('../../utils/orderDetail.js');
const config = require('../../config.js');
var orderBillId=""
Page({

  /**
   * 页面的初始数据
   */
  data: {
    zhifuActionFlag: true,
    tuikuanActionFlag: true,
    xiugaiActionFlag: false,
    shanchuActionFlag: false,
    orderBillMasterId:""
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

    //设置物流公司名称
    this.setData({ companyName: app.companyInfo.name });
    
    console.log(JSON.stringify(options.order));
    
    let tempdh = "";
    let tempon = "";
    let orderBillMasterId = "";
    if (undefined != options.order && "" != options.order) {
      let result = JSON.parse(options.order);
      // console.log(result);
      tempdh = result.id;
      tempon = (result.orderNumber == "null" || result.orderNumber == null) ? "" : result.orderNumber;
      orderBillMasterId = (result.orderBillMasterId == "null" || result.orderBillMasterId == null) ? "" : result.orderBillMasterId;
    } else if (null != options.dh && null != options.orderNumber){
      tempdh = options.dh;
      tempon = (options.orderNumber == "null" || options.orderNumber == null) ? "" : options.orderNumber;
      orderBillMasterId = (options.orderBillMasterId == "null" || options.orderBillMasterId == null) ? "" : options.orderBillMasterId;
    }
    //console.log(tempdh + "-----" + tempon);
    console.info("orderBillMasterId:"+orderBillMasterId);
    this.setData({
      orderBillMasterId: orderBillMasterId
    });
    orderBillId = orderBillMasterId
    wxbarcode.qrcode('qrcode', tempdh != null ? tempdh : (tempon != null ? tempon : ""), 300, 300);
    
    getInfo(this, tempdh, tempon, orderBillMasterId);
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  // onShareAppMessage: function () {

  // },
  /**
   * 修改
   */
  editE:function(e){
    if (this.data.order.hBackupString6 != "" && this.data.order.hBackupString6 != "undefined"){
      wx.redirectTo({
        url: '../order/driverOrder?order=' + JSON.stringify(this.data.order),
        success: function (res) { },
        fail: function (res) { },
        complete: function (res) { },
      })
    } else {
      wx.redirectTo({
        url: '../order/order?order=' + JSON.stringify(this.data.order),
        success: function (res) { },
        fail: function (res) { },
        complete: function (res) { },
      })
    }
  },
  /**
 * 支付
 */
  zhifu: function (e) {
    console.info("支付开始");
    console.info(e.target.dataset.eid);
    console.info(e.target.dataset.eid.tenantCode);
    var priceDifferences = e.target.dataset.eid.priceDifferences;
    var priceDifferencesIsPay = e.target.dataset.eid.priceDifferencesIsPay;
    var transportCost = e.target.dataset.eid.transportCost;
    var transportCostIsPay = e.target.dataset.eid.transportCostIsPay;
    var money="";
    if (priceDifferences != null && priceDifferences > 0) {
      if (priceDifferencesIsPay == "NO") {
        money = e.target.dataset.eid.priceDifferences
      } 
    } else {
      if (transportCost != null && transportCost > 0 && transportCostIsPay == 'NO') {
        money = e.target.dataset.eid.transportCost
      }
    }
    
    let submitData = {
      data: '{' +
        '"orderNo": "' + e.target.dataset.eid.id + '",' +
        '"code": "' + e.target.dataset.eid.tenantCode + '",' +
        '"openId": "' + app.openid + '",' +
        '"mobile": "' + app.loginUser.mobile + '",' +
        '"orderBillMasterId": "' + orderBillId + '",' +
        '"orderBillId": "' + orderBillId + '",' +
        '"money": "' + money + '"}'
    };
    wx.request({
      url: config.requestUrl + "payOrder/savePayOrder",
      method: "POST",
      header: {
        "Content-Type": "application/x-www-form-urlencoded"
      },
      data: submitData,
      success: function (msg) {
        wx.hideLoading()
        console.info("订单详情支付返回结果");
        console.info(msg);
          var req = msg.data.content;
        if (msg.data.msg != null && msg.data.msg != null && msg.data.msg == "微信统一下单成功") {
            console.info("调取支付");
          console.info(e.target.dataset.eid.senderMobile);
            var payOrderNo = req.payOrderNo;
            //调取支付
            wx.requestPayment(
              {
                'timeStamp': req.timeStamp,
                'nonceStr': req.nonceStr,
                'package': req.package,
                'signType': 'MD5',
                'paySign': req.paySign,
                'success': function (res) {
                  console.info("支付成功")
                  console.info(res)

                  let par = {
                    orderNo: payOrderNo,
                    mobile: e.target.dataset.eid.senderMobile,
                    payState: 1
                  };

                  wx.request({
                    url: config.requestUrl + "payOrder/updateOrderPayState",
                    method: "POST",
                    header: {
                      "Content-Type": "application/x-www-form-urlencoded"
                    },
                    data: { "data": par },
                    success: function (msg) {
                      console.info("支付回更成功");
                      wx.navigateTo({ url: "orderList" })
                    }
                  })
                },
                'fail': function (res) {
                  console.info("支付失败")
                  console.info(res)
                  if (res =="requestPayment:fail Error: connect ETIMEDOUT 58.247.205.110:443"){
                    wx.navigateTo({ url: "orderList"})
                  }
                },
              })
          }

      },
      fail: function (msg) {
        app.tip(msg, "none");
        return;
      }
    })
  },
  /**
 * 退款
 */
  tuikuan: function (e) {
    console.info("开始退款");
    console.info(e.target.dataset.eid);
    console.info(orderBillId);

    let submitData = {
      data: '{' +
        '"code": "' + e.target.dataset.eid.tenantCode + '",' +
        '"orderId": "' + e.target.dataset.eid.id + '",' +
        '"orderBillId": "' + orderBillId + '",' +
        '"refundApplyReason": "开启退款申请"}'
    };
    wx.request({
      url: config.requestUrl + "payOrder/returnPayOrderMoney",
      method: "POST",
      header: {
        "Content-Type": "application/x-www-form-urlencoded"
      },
      data: submitData,
      success: function (msg) {
        wx.hideLoading()
        console.info("退款返回结果");
        console.info(msg);
        if (msg.data.code != null && msg.data.code == "100") {
          app.tip(msg.data.msg, "none");
          wx.navigateTo({ url: "orderList" })
        } else {
          app.tip(msg.data.msg, "none");
          return;
        }
      },
      fail: function (msg) {
        app.tip(msg, "none");
        return;
      }
    })
    
  },
  /**
   * 删除
   */
delE:function(e){
  let _this = this;
  wx.showModal({
    title: '提示',
    content: '确定要删除吗？',
    success: function (sm) {
      if (sm.confirm) {
        // 用户点击了确定 可以调用删除方法了
        let tempid = e.target.dataset.eid;
        // console.log(tempid);
        wx.showLoading({ mask: true, title: "加载中" });
        wx.request({
          url: config.requestUrl + "order/deleteOrder",
          method: "POST",
          header: {
            "Content-Type": "application/x-www-form-urlencoded"//;charset=utf-8
          },
          data: { data: '{"id":' + tempid + ',"tenantCode":"' + config.tenantCode + '"}' },
          success: function (msg) {
            // console.log(msg);
            wx.hideLoading();
            if (msg.data.code == 100) {
              wx.navigateBack({
                delta: 1
              });
            } else {
              app.tip("删除失败！", 'none');
            }
          },
          fail: function (msg) {
            // console.log(msg);
            _this.setData({
              showView: false,
              message: "抱歉，没有找到相关数据！",
              imagePath: "../images/noData.png"
            });
            wx.hideLoading();
          }
        });
      } else if (sm.cancel) {
        // console.log('用户点击取消')
      }
    }
  })
  
}
});
/**
 * 获取信息
 */
function getInfo(_this, dh, orderNumber, orderBillMasterId) {
  queryInfo(dh, orderNumber, orderBillMasterId,function (msg) {
    // console.log(msg.data.content);
    let result = msg.data.content;
    if (undefined != result) {
      var transportCostIsPay = result.transportCostIsPay
      var transportCost = result.transportCost
      var transportCostRefundStatus = result.transportCostRefundStatus

      var priceDifferencesIsPay = result.priceDifferencesIsPay
      var priceDifferences = result.priceDifferences
      var priceDifferencesRefundStatus = result.priceDifferencesRefundStatus
      if (priceDifferences != null && priceDifferences>0){
        
        if (priceDifferencesIsPay=="NO"){
          _this.setData({
            zhifuActionFlag: false
          })
        } else {
          _this.setData({
            zhifuActionFlag: true
          })
        }
      } else {
        if (transportCost != null && transportCost > 0 && transportCostIsPay=='NO'){
          _this.setData({
            zhifuActionFlag: false
          })
        } else {
          _this.setData({
            zhifuActionFlag: true
          })
        }
      }

      if (priceDifferencesRefundStatus == "无" && transportCostRefundStatus == "无"){
        if (priceDifferencesIsPay == "YES" || transportCostIsPay == 'YES') {
          _this.setData({
            tuikuanActionFlag: false
          })
        } else {
          _this.setData({
            tuikuanActionFlag: true
          })
        }
      } else if (priceDifferencesRefundStatus == "无" && transportCostRefundStatus != "无") {
        if (priceDifferencesIsPay == "YES") {
          _this.setData({
            tuikuanActionFlag: false
          })
        } else {
          _this.setData({
            tuikuanActionFlag: true
          })
        }
      } else if (priceDifferencesRefundStatus != "无" && transportCostRefundStatus == "无") {
        if (transportCostIsPay == 'YES') {
          _this.setData({
            tuikuanActionFlag: false
          })
        } else {
          _this.setData({
            tuikuanActionFlag: true
          })
        }
      }


      if (priceDifferencesIsPay == "YES" || transportCostIsPay == "YES"){
        _this.setData({
          xiugaiActionFlag: true,
          shanchuActionFlag: true
        })
      }

      _this.data.order = result;
      let real = {};
      for (let t in result) {
        if (result[t] != null && result[t] != "null" && result[t] != "undefined") {
          real[t] = result[t];
        }
      }
      // console.log(real);
      // real.senderAddress = real.senderAddress.replace('⊙', '');
      real.senderAddress = real.senderAddress != undefined ? real.senderAddress.replace('⊙', '') : "";
      _this.setData({ res: real });
    }
  })
}

/**
 * 请求数据
 */
function queryInfo(dh, orderNumber, orderBillMasterId,callback) {
  console.info("请求参数");
  console.info(orderBillMasterId);
  wx.showLoading({ mask: true, title: "加载中" });
  wx.request({
    url: config.requestUrl + "order/getOrderInfo",
    method: "GET",
    header: {
      "Content-Type": "application/x-www-form-urlencoded"//;charset=utf-8
    },
    data: { "id": dh, "code": config.tenantCode, "orderNo": orderNumber, "orderBillMasterId": orderBillMasterId },
    success: function (msg) {
      console.info("未处理订单返回结果");
      console.info(msg);
      callback(msg);
      wx.hideLoading();
    },
    fail: function (msg) {
      // console.log(msg);
      _this.setData({
        showView: false,
        message: "抱歉，没有找到相关数据！",
        imagePath: "../images/noData.png"
      });
      wx.hideLoading();
    }
  });
}